package com.zenchn.config.druid;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * BusinessDataSourcesConfig：
 *  业务库 数据源配置
 * @author dingxinfa
 * @date 2020-06-12 11:01
 */
@Configuration
@MapperScan(basePackages = {"com.zenchn.dao","com.zenchn.dynamic"}, sqlSessionFactoryRef = "businessSqlSessionFactory")
public class BusinessDataSourcesConfig {

    private static final String MAPPER_LOCATIONS = "classpath:com/zenchn/dao/mapper/*.xml";
    private static final String TYPE_ALIASES_PACKAGE ="com.zenchn.model";


    @ConfigurationProperties("spring.datasource.druid.business")
    @Primary
    @Bean(name = "businessDataSource")
    public DataSource businessDataSource() {
        return DruidDataSourceBuilder.create().build();
    }


    @Primary
    @Bean(name = "businessTransactionManager")
    public DataSourceTransactionManager businessTransactionManager() {
        return new DataSourceTransactionManager(businessDataSource());
    }

    @Primary
    @Bean(name = "businessSqlSessionFactory")
    public SqlSessionFactory businessSqlSessionFactory(@Qualifier("businessDataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATIONS));
        sessionFactoryBean.setTypeAliasesPackage(TYPE_ALIASES_PACKAGE);
        return sessionFactoryBean.getObject();
    }

}
